import axios from 'axios';
import Mymessage from './Mymessage.js'
import { ElLoading } from 'element-plus';
import router from '../router/index.js';

const contentTypeFrom = 'application/x-www-form-urlencoded;charset=UTF-8'
const contentTypeJson = 'application/json;charset=UTF-8'
const responseTypeJson = 'json'


let loading = null
const interceptor = axios.create({
    baseURL: 'api/',
    timeout: 10 * 1000 * 1000,
})
// 添加请求拦截器
interceptor.interceptors.request.use(
    function (config) {

        if (config.showLoading) {
            loading = ElLoading.service({
                lock: true,
                text: 'Loading',
                background: 'rgba(0, 0, 0, 0.7)'
            })
        }
        return config;
    },
    function (error) {
        if (config.showLoading && loading) {
            loading.close()
        }
        Mymessage.error("请求发送失败")
        return Promise.reject("请求发送失败");
    });

// 添加响应拦截器
interceptor.interceptors.response.use(
    function (response) {
        const { showLoading, errorCallback, showError = true, responseType } = response.config
        if (showLoading && loading) {
            loading.close()
        }
        const responseData = response.data
        if (responseType === 'blob' || responseType === 'arraybuffer') {
            return responseData
        }
        //正常请求
        if (responseData.code === 200) {
            return responseData
        } else if (responseData.code === 901) {
            router.push("/login?redirect=" + encodeURI(router.currentRoute.value.Path))
            return Promise.reject({ showError: false, msg: "登录超时" })
        } else {
            if (errorCallback) {
                errorCallback(responseData.info)
            }
            return Promise.reject({ showError: showError, msg: responseData.info })
        }


    },
    function (error) {
        if (error.config.showLoading && loading) loading.close()

        return Promise.reject({ showError: true, msg: "网络异常" });
    });




const request = (config) => {

    const { url, params, dataType, showLoading = true, responseType = responseTypeJson } = config

    let contentType = contentTypeFrom
    let formData = new FormData()
    for (let key in params) {
        if (Object.hasOwnProperty.call(params, key)) {
            const element = params[key];
            formData.append(key, element)
        }
    }
    if (dataType === 'json' && dataType !== null) {
        contentType = contentTypeJson

    }
    let headers = {
        'Content-Type': contentType,
        'X-Requested-With': 'XMLHttpRequest'
    }

    return interceptor.post(url, formData, {
        onUploadProgress: function (progressEvent) {
            if (config.uploadProgressCallback) {
                config.uploadProgressCallback(progressEvent)
            }
        },
        responseType: responseType,
        headers: headers,
        showLoading: showLoading,
        errorCallback: config.errorCallback,
        showError: config.showError,


    }).catch(error => {
        console.log(error);

        if (error.showError) {
            Mymessage.error(error.msg)
        }
        return Promise.reject(error)
    })
}

export default request


